/**
 * 菜品详情页面组件
 * 展示单个菜品的详细信息，包括图片、描述、价格、评价等
 */
import { View, Text, Image, Button, ScrollView } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import { useState, useEffect } from 'react'
import { useAppContext } from '../../store'
import { CloudDataManager } from '../../utils/cloud'
import './detail.scss'

/**
 * 菜品详情页面组件
 * 提供菜品信息展示、添加到购物车、评价查看等功能
 */
export default function DishDetail() {
  const router = useRouter()
  const { state } = useAppContext()
  
  // 菜品详情数据
  const [dish, setDish] = useState<any>(null)
  // 加载状态
  const [loading, setLoading] = useState(true)
  // 添加到购物车状态
  const [addingToCart, setAddingToCart] = useState(false)
  // 用户评价列表
  const [reviews, setReviews] = useState<any[]>([])
  // 当前用户评价
  const [userReview, setUserReview] = useState<any>(null)

  /**
   * 组件挂载时加载菜品详情
   */
  useEffect(() => {
    if (router.params.id) {
      loadDishDetail(router.params.id)
    }
  }, [router.params.id])

  /**
   * 加载菜品详情数据
   * @param dishId 菜品ID
   */
  const loadDishDetail = async (dishId: string) => {
    try {
      setLoading(true)
      
      // 并行加载菜品信息和评价数据
      const [dishData, reviewsData] = await Promise.all([
        CloudDataManager.getData('dishes', dishId),
        CloudDataManager.getAllData('ratings', { dishId })
      ])
      
      if (dishData) {
        setDish(dishData)
        setReviews(reviewsData)
        
        // 如果用户已登录，查找用户评价
        if (state.currentUser) {
          const userReviewData = reviewsData.find(
            (review: any) => review.userId === state.currentUser!.id
          )
          setUserReview(userReviewData || null)
        }
      } else {
        Taro.showToast({
          title: '菜品不存在',
          icon: 'error'
        })
        Taro.navigateBack()
      }
    } catch (error) {
      console.error('加载菜品详情失败:', error)
      Taro.showToast({
        title: '加载失败',
        icon: 'error'
      })
    } finally {
      setLoading(false)
    }
  }

  /**
   * 添加到购物车
   */
  const addToCart = async () => {
    if (!dish) return
    
    try {
      setAddingToCart(true)
      
      // 获取当前购物车
      const cart = Taro.getStorageSync('cart') || []
      
      // 检查是否已在购物车中
      const existingItem = cart.find((item: any) => item.id === dish.id)
      
      if (existingItem) {
        // 如果已存在，增加数量
        existingItem.quantity += 1
      } else {
        // 如果不存在，添加新项目
        cart.push({
          ...dish,
          quantity: 1,
          addedAt: new Date()
        })
      }
      
      // 保存到本地存储
      Taro.setStorageSync('cart', cart)
      
      // 显示成功提示
      Taro.showToast({
        title: '已添加到购物车',
        icon: 'success'
      })
      
    } catch (error) {
      console.error('添加到购物车失败:', error)
      Taro.showToast({
        title: '添加失败',
        icon: 'error'
      })
    } finally {
      setAddingToCart(false)
    }
  }

  /**
   * 跳转到购物车页面
   */
  const navigateToCart = () => {
    Taro.navigateTo({
      url: '/pages/cart/index'
    })
  }

  /**
   * 返回上一页
   */
  const handleBack = () => {
    Taro.navigateBack()
  }

  /**
   * 计算平均评分
   * @returns number 平均评分
   */
  const calculateAverageRating = () => {
    if (reviews.length === 0) return 0
    
    const totalRating = reviews.reduce((sum, review) => sum + review.rating, 0)
    return (totalRating / reviews.length).toFixed(1)
  }

  /**
   * 获取评分星级显示
   * @param rating 评分
   * @returns string 星级字符串
   */
  const getStarRating = (rating: number) => {
    const fullStars = Math.floor(rating)
    const hasHalfStar = rating % 1 >= 0.5
    const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0)
    
    return '★'.repeat(fullStars) + (hasHalfStar ? '☆' : '') + '☆'.repeat(emptyStars)
  }

  /**
   * 格式化评价时间
   * @param date 日期
   * @returns string 格式化后的时间
   */
  const formatReviewTime = (date: Date) => {
    const reviewDate = new Date(date)
    const now = new Date()
    const diffTime = now.getTime() - reviewDate.getTime()
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
    
    if (diffDays === 0) {
      return '今天'
    } else if (diffDays === 1) {
      return '昨天'
    } else if (diffDays < 7) {
      return `${diffDays}天前`
    } else {
      return reviewDate.toLocaleDateString()
    }
  }

  if (loading) {
    return (
      <View className='dish-detail'>
        <View className='loading-container'>
          <Text className='loading-text'>加载中...</Text>
        </View>
      </View>
    )
  }

  if (!dish) {
    return (
      <View className='dish-detail'>
        <View className='error-container'>
          <Text className='error-text'>菜品不存在</Text>
          <Button className='back-btn' onClick={handleBack}>
            返回
          </Button>
        </View>
      </View>
    )
  }

  return (
    <View className='dish-detail'>
      {/* 页面头部 */}
      <View className='header'>
        <Button className='back-button' onClick={handleBack}>
          返回
        </Button>
        <Text className='title'>菜品详情</Text>
      </View>

      {/* 菜品信息 */}
      <ScrollView className='dish-content' scrollY>
        {/* 菜品图片 */}
        <View className='dish-image-container'>
          <Image 
            className='dish-image' 
            src={dish.image || '/assets/images/default-dish.png'}
            mode='aspectFill'
          />
          {!dish.available && (
            <View className='dish-unavailable'>
              <Text className='unavailable-text'>已售罄</Text>
            </View>
          )}
        </View>

        {/* 菜品基本信息 */}
        <View className='dish-info'>
          <Text className='dish-name'>{dish.name}</Text>
          <Text className='dish-description'>{dish.description}</Text>
          
          <View className='dish-meta'>
            <Text className='dish-category'>分类：{dish.category}</Text>
            <Text className='dish-price'>¥{dish.price}</Text>
          </View>
        </View>

        {/* 评价信息 */}
        <View className='reviews-section'>
          <View className='reviews-header'>
            <Text className='reviews-title'>用户评价</Text>
            <View className='rating-summary'>
              <Text className='average-rating'>{calculateAverageRating()}</Text>
              <Text className='star-rating'>{getStarRating(Number(calculateAverageRating()))}</Text>
              <Text className='review-count'>({reviews.length}条评价)</Text>
            </View>
          </View>

          {/* 评价列表 */}
          {reviews.length === 0 ? (
            <View className='no-reviews'>
              <Text className='no-reviews-text'>暂无评价</Text>
            </View>
          ) : (
            <View className='reviews-list'>
              {reviews.map((review, index) => (
                <View key={index} className='review-item'>
                  <View className='review-header'>
                    <Text className='reviewer-name'>{review.userName || '匿名用户'}</Text>
                    <View className='review-rating'>
                      <Text className='star-rating'>{getStarRating(review.rating)}</Text>
                      <Text className='rating-value'>{review.rating}</Text>
                    </View>
                  </View>
                  
                  {review.comment && (
                    <Text className='review-comment'>{review.comment}</Text>
                  )}
                  
                  <Text className='review-time'>{formatReviewTime(review.createdAt)}</Text>
                </View>
              ))}
            </View>
          )}
        </View>
      </ScrollView>

      {/* 底部操作按钮 */}
      <View className='action-buttons'>
        {dish.available ? (
          <>
            <Button 
              className='action-btn add-to-cart-btn'
              disabled={addingToCart}
              onClick={addToCart}
            >
              {addingToCart ? '添加中...' : '加入购物车'}
            </Button>
            <Button 
              className='action-btn cart-btn'
              onClick={navigateToCart}
            >
              查看购物车
            </Button>
          </>
        ) : (
          <Text className='unavailable-notice'>该菜品暂时不可用</Text>
        )}
      </View>
    </View>
  )
} 